<template>
  <div>
    <!-- 文件上传 -->
    <el-upload
      :data="qiniuToken"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      :before-remove="beforeRemove"
      :file-list="$files"
      :on-preview="watchPDF"
      :limit="limit"
      class="upload-demo"
      action="http://upload.qiniu.com/"
      accept="application/pdf"
    >
      <div>
        <div class="display_flex">
          <el-button size="small" type="primary">点击上传</el-button>
        </div>
        <div slot="tip" class="el-upload__tip" style="margin-top:0">(提示：请上传pdf格式文件)</div>
      </div>
    </el-upload>
  </div>
</template>

<script>
export default {
  name: '',
  components: {},
  mixins: [],
  props: {
    files: {
      type: Array,
      default () {
        return []
      }
    },
    fileName: {
      type: String,
      default: ''
    },
    isDel: {
      type: Boolean,
      default: false
    },
    token: {
      required: true,
      type: String
    },
    // 限制数量
    limit: {
      type: Number,
      default: 99999
    }
  },
  data () {
    return {
      qiniuToken: {
        token: ''
      },
      loading: null
    }
  },
  computed: {
    $files: {
      get () {
        return this.files
      },
      set (val) {
        console.log(val)
        this.$emit('update:files', val)
      }
    }
  },
  watch: {
    token (cur) {
      if (cur) {
        this.qiniuToken.token = this.token
      }
    }
  },
  created () {
    this.qiniuToken.token = this.token
  },
  mounted () {},
  destroyed () {},
  methods: {
    // 移除文件时的钩子
    handleRemove (file, fileList) {
      console.log(fileList)
      this.$files.splice(this.$files.indexOf(file), 1)
      this.hideUpload = fileList.length >= this.limit
    },
    // 上传成功时的钩子
    handleSuccess (res, file, fileList) {
      fileList.map(v => {
        if (v.response) {
          v.url = this.$qiniu + v.response.key
        }
      })
      this.$files = fileList
      this.hideUpload = fileList.length >= this.limit
      this.loading.close()
    },
    // 查看pdf
    watchPDF (file) {
      window.open(file.url, '_blank')
    },
    // 上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUpload () {
      this.loading = this.$loading(this.$loadingOptions)
    },
    beforeRemove () {
      this.$files = []
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
